import PageModal from '@/components/page-modal'
import { ref } from 'vue'

type CallbackFn = (item?: any) => void
export function useModal(
  modalConfig?: any,
  newCb?: CallbackFn,
  editCb?: CallbackFn
) {
  /**
   * pageModalRef 获取pageModal 组件ref
   */
  const pageModalRef = ref<InstanceType<typeof PageModal>>()
  /**
   * handleNewData 新建按钮的回调
   */
  const handleNewData = () => {
    defaultInfo.value = {}
    modalConfig.new_editName = modalConfig.new_editName?.replace(
      /^.{2}/g,
      '新建'
    )
    if (pageModalRef.value) {
      pageModalRef.value.dialogVisible = true
    }
    modalConfig.confirmDisable = false
    newCb && newCb()
  }
  const defaultInfo = ref({})
  /**
   * handleEditData 点击编辑按钮的回调
   * @param item 表格每一项的数据
   */
  const handleEditData = (item: any) => {
    defaultInfo.value = { ...item }
    modalConfig.new_editName = modalConfig.new_editName?.replace(
      /^.{2}/g,
      '编辑'
    )
    if (pageModalRef.value) {
      pageModalRef.value.dialogVisible = true
    }
    modalConfig.confirmDisable = false
    editCb && editCb(item)
  }

  const handleLookData = (item: any) => {
    defaultInfo.value = { ...item }
    modalConfig.new_editName = modalConfig.new_editName?.replace(
      /^.{2}/g,
      '查看'
    )
    if (pageModalRef.value) {
      pageModalRef.value.dialogVisible = true
    }
    modalConfig.confirmDisable = true
    editCb && editCb(item)
  }

  return [
    handleNewData,
    handleEditData,
    handleLookData,
    defaultInfo,
    pageModalRef
  ]
}
